package com.hema.auction.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hema.auction.activity.LoginActivity;
import com.hema.auction.bean.ProfileInfo;
import com.hema.auction.http.HttpInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.listener.RequestCallBack;
import com.hema.auction.utils.ACache;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.manager.SPManager;
import com.hema.auction.widget.dialog.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Set;

import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;
import okhttp3.Response;

/**
 * author by john
 * fragment基类
 */
public abstract class BaseFragment extends Fragment implements RequestCallBack, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener {

    protected int UiThreadId;
    protected SPManager spManager;
    protected LoadingDialog progressDialog;
    protected ACache aCache;
    protected View view;
    protected ProfileInfo profileInfo;
    protected boolean isLogin;
    protected int pageIndex = 1, pageSize = 10;
    protected boolean isAutoDismissDialog = true;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        UiThreadId = Process.myTid();
        spManager = SPManager.getInstance(getActivity());
        isLogin = spManager.islogin();
        aCache = ACache.get(getActivity());
        getProfileInfo();
        init();
    }

    @Override
    public void onResume() {
        super.onResume();
        isLogin = spManager.islogin();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getLayout(), container, false);
        return view;
    }

    protected abstract int getLayout();

    protected void init() {
        ButterKnife.bind(this, view);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == Constant.HTTP_TYPE_ONRESPONSE) {
                HttpInfo httpInfo = (HttpInfo) msg.obj;
                if (isAutoDismissDialog)dismissProgressDialog();
                try {
                    LogUtils.d("------onSuccess =" + httpInfo.getResult());
                    onSuccess(httpInfo.getHttpTag(), httpInfo.getCall(), new JSONObject(httpInfo.getResult()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (msg.what == Constant.HTTP_TYPE_ONFAILEURE) {
                dismissProgressDialog();
                HttpInfo httpInfo = (HttpInfo) msg.obj;
                onError(httpInfo.getHttpTag(), httpInfo.getCall(), httpInfo.getE());
            } else if (msg.what == Constant.HTTP_TYPE_ONFINISH) {
                onFinish((HttpTag) msg.obj);
            } else {
                onHandleMessage(msg);
            }
        }
    };

    protected Handler getDefaultHandler() {
        return mHandler;
    }

    protected void onHandleMessage(Message msg) {

    }

    protected void post(Runnable r) {
        mHandler.post(r);
    }

    private void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
    }

    private void showToast(int resId) {
        Toast.makeText(getActivity(), resId, Toast.LENGTH_LONG).show();
    }


    protected void showToastSafe(final String text) {
        if (Process.myTid() == UiThreadId) {
            showToast(text);
        } else {
            post(new Runnable() {

                @Override
                public void run() {
                    showToast(text);
                }
            });
        }
    }

    protected void showToastSafe(final int resId) {
        if (Process.myTid() == UiThreadId) {
            showToast(resId);
        } else {
            post(new Runnable() {

                @Override
                public void run() {
                    showToast(resId);
                }
            });
        }
    }

    protected void showToastSafe(JSONObject json) {
        try {
            if (!json.isNull("errmsg")) {
                final String message = json.getString("errmsg");
                if (Process.myTid() == UiThreadId) {
                    showToast(message);
                } else {
                    post(new Runnable() {

                        @Override
                        public void run() {
                            showToast(message);
                        }
                    });
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }


    protected void intentTo(Class<?> cs) {
        startActivity(new Intent(getActivity(), cs));
    }

    protected void intentTo(Class<?> cs, Bundle extra) {
        startActivity(new Intent(getActivity(), cs).putExtras(extra));
    }

    protected void intentToForResult(Class<?> cs, int code) {
        startActivityForResult(new Intent(getActivity(), cs), code);
    }

    protected void intentToForResult(Class<?> cs, Bundle extra, int code) {
        startActivityForResult(new Intent(getActivity(), cs).putExtras(extra), code);
    }

    protected void showProgressDialog() {
        if (progressDialog == null)
            progressDialog = new LoadingDialog();
        progressDialog.show(getChildFragmentManager());
//        progressDialog.setDesc(getString(R.string.loading));
    }


    protected void showProgressDialog(boolean cancelable) {
        if (progressDialog == null)
            progressDialog = new LoadingDialog();
        progressDialog.setCancelable(cancelable);
        progressDialog.show(getChildFragmentManager());
    }

    protected void showProgressDialog(String message) {
        if (progressDialog == null)
            progressDialog = new LoadingDialog();
        progressDialog.setCancelable(true);
        progressDialog.show(getChildFragmentManager());
        progressDialog.setMessage(message);
    }

    protected void showProgressDialog(int message) {
        if (progressDialog == null)
            progressDialog = new LoadingDialog();
        progressDialog.setCancelable(true);
        progressDialog.show(getChildFragmentManager());
        progressDialog.setMessage(getString(message));
    }

    protected void dismissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onFailure(final HttpTag httpTag, final Call call, final IOException e) {
        HttpInfo httpInfo = new HttpInfo(httpTag, call, e);
        Message message = new Message();
        message.what = Constant.HTTP_TYPE_ONFAILEURE;
        message.obj = httpInfo;
        mHandler.sendMessage(message);
    }

    @Override
    public void onResponse(final HttpTag httpTag, final Call call, final Response response) {
        if (response.isSuccessful()) {
            try {
                String result = response.body().string();
                HttpInfo httpInfo = new HttpInfo(httpTag, call, result);
                Message message = new Message();
                message.what = Constant.HTTP_TYPE_ONRESPONSE;
                message.obj = httpInfo;
                mHandler.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            HttpInfo httpInfo = new HttpInfo(httpTag, call, new IOException());
            Message message = new Message();
            message.what = Constant.HTTP_TYPE_ONFAILEURE;
            message.obj = httpInfo;
            mHandler.sendMessage(message);
        }

    }

    @Override
    public void onRequestFinish(HttpTag eventCode) {
        Message message = new Message();
        message.what = Constant.HTTP_TYPE_ONFINISH;
        message.obj = eventCode;
        mHandler.sendMessage(message);
    }

    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {

    }

    protected void onError(HttpTag httpTag, Call call, IOException e) {
        LogUtils.d("------onError = " + e.toString());
    }

    protected void onFinish(HttpTag httpTag) {

    }

    protected void setOnRefreshView() {

    }

    @Override
    public void onRefresh() {

    }

    protected void onLoadMore() {

    }

    @Override
    public void onLoadMoreRequested() {
        onLoadMore();
    }

    protected ProfileInfo getProfileInfo() {
        profileInfo = (ProfileInfo) aCache.getAsObject(Constant.CACHE_KEY_PROFILE);
        if(profileInfo == null)profileInfo = new ProfileInfo();
        return profileInfo;
    }


    protected void updateProfile(ProfileInfo profileInfo) {
        this.profileInfo = profileInfo;
        aCache.put(Constant.CACHE_KEY_PROFILE, profileInfo);
    }

    protected void updateProfile() {
        aCache.put(Constant.CACHE_KEY_PROFILE, profileInfo);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    protected void goLogin() {
        intentTo(LoginActivity.class);
    }


    protected void setAlisa(){
        JPushInterface.setAliasAndTags(getActivity().getApplicationContext(),
                profileInfo.getAlisa(),
                null,
                new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        switch (i) {
                            case 0:
                                LogUtils.i("--------alisa success = "+s);//150190432021
                                break;
                            case 6002:
                                LogUtils.i("--------alisa fail = "+s);
                                break;
                            default:
                                LogUtils.i("--------alisa erroe = "+s);
                        }
                    }
                });
    }
}
